package com.example.demo.filter;

import com.example.demo.entity.Store;
import com.example.demo.entity.User;
import com.example.demo.service.StoreService;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class UserFormAuthenticationFilter extends FormAuthenticationFilter {


    @Autowired
    StoreService storeService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        Subject subject=this.getSubject(request, response);

//若前者为false证明不是登陆过的，同时后者为true；证明是通过记住我功能进来的；
        if(!subject.isAuthenticated() && subject.isRemembered()){
//看session是否为空
            Session session=subject.getSession(true);
            if(session.getAttribute("loginUser")==null){
            User loginUser=(User)subject.getPrincipal();
            session.setAttribute("loginUser",loginUser);


                if(session.getAttribute("loginStore")==null){
                    Store store=storeService.findStoreByUserId(loginUser.getUserId());
                    session.setAttribute("loginStore",store);
                }





            }




        }
        return true;

    }
}
